Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

题目大意:求给定字符串数组的最长相同前缀

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/5
 * 复杂度 O(K*N)
 */
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0 ) return "";

        int len = strs[0].length();
        char[] result = new char[len];
        int i;
        for (i = 0; i < len; i++) {
            int j;
            for (j = 1; j < strs.length; j++) {
                if (strs[j].length() <= i)break;
                if (strs[j].charAt(i) != strs[0].charAt(i))break;
            }
            if (j != strs.length)break;
        }
        return strs[0].substring(0,i);
    }
}
gzdaijie            updated 2016-05-05 21:32:08

results matching ""

    No results matching ""